﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace KgUtils.EntityFramework
{
    public static partial class ObjectContextExtension
    {
        public static int ExecuteNonQueryCommand(this ObjectContext context, string command)
        {
            DbConnection connection = ((EntityConnection)context.Connection).StoreConnection;
            bool opening = (connection.State == ConnectionState.Closed);
            if (opening)
                connection.Open();

            DbCommand cmd = connection.CreateCommand();
            cmd.CommandText = command;
            cmd.CommandType = CommandType.Text;
            try
            {
                return cmd.ExecuteNonQuery();
            }
            finally
            {
                if (opening && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        public static void ExecuteStoredProc(this ObjectContext source, string pStoredProcName, List<EntityParameter> pStoredProcParams)
        {
            Guard.AssertNotNull(source, "source");

            using (DbCommand command = source.Connection.CreateCommand())
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = String.Concat(source.GetType().Name, ".", pStoredProcName);

                if (pStoredProcParams != null)
                {
                    foreach (EntityParameter tgtParameter in pStoredProcParams)
                    {
                        command.Parameters.Add(tgtParameter);
                    }
                }

                if (source.Connection.State == ConnectionState.Closed)
                {
                    source.Connection.Open();
                }
                command.ExecuteNonQuery();
            }
        }

        public static EntityKey CreateEntityKey(this ObjectContext context, EntityObject entity, object value)
        {
            return new EntityKey(context.GetEntityName(entity.GetType(), true), entity.GetEntityPrimaryKeyName(), value);
        }

        public static string GetEntityName(this ObjectContext context, Type entityType, bool includeContextName = false)
        {
            if (includeContextName)
                return String.Concat(context.GetType().Name, ".", entityType.Name);
            else
                return entityType.Name;
        }
    }
}
